package IC.asm;

import IC.AST.nodes.FormalDecl;
import IC.AST.nodes.MethodDecl;
import IC.AST.nodes.Program;
import IC.AST.nodes.VarDeclStmt;
import IC.Analyzer.SymTabEntry;


public class PreProcessor extends IC.lir.PreProcessor {

	private int localVarOffset;
	private int paramOffset;
	private int localVarsCount;
	private PreProcessor(Program root) {
		super(root);
		localVarOffset = -4-12;
		paramOffset = +8;
	}
	
	public static void Process(Program prog) 
	throws Exception 
	{
		PreProcessor p = new PreProcessor(prog);
		prog.accept(p, null);
		prog.getMain().setLabel("__ic_main");
	}

	public Object visit(VarDeclStmt that, Object context) throws Exception {

		SymTabEntry STEnt = that.getSymTab().resolve(that.getVar().getID());
		STEnt.setOffset(localVarOffset);
		
		localVarOffset -= 4;
		localVarsCount++;
		return super.visit(that, context);
	}

	public Object visit(MethodDecl that, Object context) throws Exception {
		localVarOffset = -4-12;
		paramOffset = +8;
		localVarsCount = 0;
		
		if(!that.isStatic()) {
			paramOffset += 4;
		}
		
		SymTabEntry STEnt;
		for(FormalDecl fd : that.getFormals()) {
			STEnt = that.getSymTab().resolve(fd.getID());
			STEnt.setOffset(paramOffset);
	
			//System.out.println(fd.getID()+" : "+paramOffset);
			paramOffset += 4;
		}
			
		super.visit(that, context);
		
		that.setNumLocals(localVarsCount);
		
		//System.out.println("localVarsCount:"+localVarsCount);	
		return null;
	}

}
